<?php
class ApiController extends Controller {
	// Uncomment the following methods and override them if needed
	public function actionAddme() {
		if (isset ( $_POST ['APPID'] )) {
			// if($param!=""){
			// Authenticate(check client's APPID with its URL) Client's APPID. If Authenticated add contact
			$resp = $this->validateMe ();
			$temp = CJSON::decode ( $resp );
			// print_r($resp);
			// exit();
			if ($temp ['type'] == 'Error') {
				header ( "Access-Control-Allow-Origin: *" );
				echo $resp;
				// redirect to registration page..
				exit ();
			} else if ($temp ['type'] == 'Ok' && $temp ['status'] == 'AddContact') {
				// Add contact
				try {
					$model = new Contact ();
					$model->ip_address = $_SERVER ['REMOTE_ADDR'];
					$model->activity_timestamp = Date ( 'Y-m-d H:i:s' );
					$model->client_id = $_POST ['APPID'];
					$model->contact_id = substr ( (time () * rand ()), 0, 10 );
					// Contact::model()->attributes = $model;
					if ($model->save ()) {
						$arr = array (
								'status' => 'OK',
								'ip' => $_SERVER ['REMOTE_ADDR'],
								'name' => $_POST ['host'],
								'contact_id' => $model->contact_id 
						);
						$command = Yii::app ()->db->createCommand ( 'call resolve_list(' . $model->client_id . ')' );
						$command->execute ();
						header ( "Access-Control-Allow-Origin: *" );
						echo $this->sendJSONResponse ( $arr );
					} else {
						header ( "Access-Control-Allow-Origin: *" );
						print_r ( $model->errors );
					}
				} catch ( Exception $e ) {
					header ( "Access-Control-Allow-Origin: *" );
					echo $e->getMessage ();
				}
			} else {
				header ( "Access-Control-Allow-Origin: *" );
				echo "Visited..";
			}
		}
		/*
		 * else{
		 * $arr = array('controller' => $this->id, 'action' => $this->action->id, 'status' => 'ERROR');
		 * }
		 */
	}
	public function sendJSONResponse($arr) {
		// header("Access-Control-Allow-Origin: *");
		return CJSON::encode ( $arr );
	}
	public function addLogEntries($contact_id, $client_id) {
		$logentry = new LogEntries ();
		$logentry->page_name_visited = $_POST ['url']; // $_SERVER['PHP_SELF'];
		$logentry->client_id = $client_id;
		$logentry->contact_id = $contact_id;
		$logentry->form_submitted = "";
		$logentry->visit_time = Date ( 'Y-m-d H:i:s' );
		if (! $logentry->save ()) {
			return false;
		}
		// echo "Save Logentry: <br/>".CJSON::encode($logentry)."<br/><br/><br/>";
		return true;
	}
	public function updateContactActivity($contact_id) {
		$contact = Contact::model ()->findByPk ( $contact_id );
		if ($contact != null) {
			$contact->activity_timestamp = Date ( 'Y-m-d H:i:s' );
			if (! $contact->save ()) {
				return false;
				// echo CJSON::encode($contact)."<br/>".CJSON::encode($contact->errors)."<br/><br/><br/>";
			}
		}
		return true;
	}
	public function actionMyDetails() {
		if (isset ( $_POST ['APPID'] )) {
			$resp = CJSON::decode ( $this->validateMe () );
			header ( "Access-Control-Allow-Origin: *" );
			if ($resp ['type'] == 'Error') {
				echo $resp;
				exit ();
			} else if ($resp ['type'] == 'Ok' && $resp ['status'] == 'Exists') {
				// save form fields as properties
				$properties = Properties::model ()->fetchProperties ( $_POST ['APPID'] );
				$propertyFields = array ();
				// $available_fields = array();
				foreach ( $properties as $property ) {
					if ($property [2] == "false" && $property [3] == "false") {
						// property field
						if (isset ( $_POST [$property [0]] )) {
							array_push ( $propertyFields, $property );
							
							$request = array (
									':prop_id' => $property [4] 
							);
							$cp = ContactProperties::model ()->find ( "prop_id=:prop_id", $request );
							if ($cp == null) {
								$contactProperties = new ContactProperties ();
								// $contactProperties->setAttribute($property[0], $_POST[$field]);
								$contactProperties->prop_id = $property [4];
								$contactProperties->contact_id = $_POST ['kntktde'];
								$contactProperties->prop_val = $_POST [$property [0]];
								
								if ($contactProperties->save ()) {
									echo "Contact Properties Saved";
									// exit();
								} else {
									echo $contactProperties->errors;
								}
							} else {
								// $contactProperties->setAttribute($property[0], $_POST[$field]);
								$cp->prop_id = $property [4];
								$cp->contact_id = $_POST ['kntktde'];
								$cp->prop_val = $_POST [$property [0]];
								
								if ($cp->validate ()) {
									if ($cp->update ()) {
										echo "Contact Properties Updated";
									} else {
										echo $cp->errors;
									}
								} else {
									echo $cp->errors;
								}
							}
						}
					}
				}
				
				// call list resolution proc
				// call execute action
				$logentry = new LogEntries ();
				$logentry->page_name_visited = $_POST ['url']; // $_SERVER['PHP_SELF'];
				$logentry->client_id = $_POST ['APPID'];
				$logentry->contact_id = $_POST ['kntktde'];
				$logentry->form_submitted = $_POST ['formName'];
				$logentry->visit_time = Date ( 'Y-m-d H:i:s' );
				if ($logentry->save ()) {
					echo "<br/>logged..";
				}
			} else {
				header ( "Access-Control-Allow-Origin: *" );
				echo "Unknown..";
			}
		} else {
			header ( "Access-Control-Allow-Origin: *" );
			echo "No APPID";
		}
	}
	public function validateMe() {
		$client = Client::model ()->findByPk ( $_POST ['APPID'] );
		if ($client == null) {
			return $this->sendJSONResponse ( array (
					'status' => 'Unauthorised',
					"message" => "Unauthenticated Client",
					'type' => 'Error' 
			) );
			// redirect to register page..
			// $this->redirect('Client/Create');
		}
		if ($client->website_url != $_POST ['host']) {
			return $this->sendJSONResponse ( array (
					'status' => 'Unauthorised',
					'message' => 'Unauthenticated Client',
					'type' => 'Error' 
			) );
			// redirect to register page..
			// $this->redirect('Client/Create');
		}
		if (isset ( $_POST ['kntktde'] ) && $_POST ['kntktde'] != "") {
			$this->updateContactActivity ( $_POST ['kntktde'] );
			$logged = $this->addLogEntries ( $_POST ['kntktde'], $_POST ['APPID'] );
			return $this->sendJSONResponse ( array (
					'status' => 'Exists',
					'message' => $_POST ['kntktde'],
					'type' => 'Ok' 
			) );
		}
		return $this->sendJSONResponse ( array (
				'status' => 'AddContact',
				'message' => '',
				'type' => 'Ok' 
		) );
	}
	
public function actionExecutestep($list_id, $contact_id) {
		$sHost = "localhost";
		$sUsername = "root";
		$sPassword = "admin";
		$sDb = "cmadb";
		
		$stepModels = Steps::model ()->findAll ( "list_id=" . $list_id );
		foreach ( $stepModels as $stepModel ) {
			$actionModelArray = Actions::model ()->findAll ( "step_id=" . $stepModel->step_id );
			
			$con = mysql_connect ( $sHost, $sUsername, $sPassword ) or die ( 'Could not connect to MySQL server: ' . mysql_error () );
			echo "Connected to MySQL server";
			
			mysql_select_db ( $sDb ) or die ( 'Could not connect to database' . mysql_error () );
			echo "Connected to Database";
			
			$delayMins = $stepModel->delay_days * 1440 + $stepModel->delay_hours * 60 + $stepModel->delay_mins;
			
			foreach ( $actionModelArray as $actionModel ) {
				if ($actionModel->action_type == 'update_prop') {
					$query = "CREATE EVENT myevent" . $actionModel->action_id . " ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL " . $delayMins . " MINUTE
						  DO update contact_properties cp JOIN action_prop ap on cp.prop_id = ap.prop_id
						  set cp.prop_val = ap.prop_val where cp.contact_id = " . $contact_id . " and ap.action_id =" . $actionModel->action_id . ";";
					$sResult = mysql_query ( $query ) or die ( mysql_error () );
					echo "Update Prop Done";
				}
				
				if ($actionModel->action_type == 'send_mail') {
					$query = "CREATE EVENT myevent" . $actionModel->action_id . " ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL " . $delayMins . " MINUTE
						  DO insert into mail_store_new(mail_id, status, sent_time) values
						 ((select b.mail_id from actions a join action_mail b on a.action_id = b.action_id where a.action_id = " . $actionModel->action_id . "),'READY_TO_SEND',CURRENT_TIMESTAMP)";
					;
					$sResult = mysql_query ( $query ) or die ( mysql_error () );
					echo "Mail Send Done";
				}
			}
		}
	}
}